package com.hzit.web.controller;


import com.hzit.net.util.SecurityKitUtil;
import com.hzit.web.bean.*;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.*;

@Controller
public class MessageController {
       private String token="bj2004_rzwl_token";
       @GetMapping("/message")
       @ResponseBody
    public String message(String signature,String timestamp,String nonce,String echostr){

        String [] strArr={token,timestamp,nonce};
        Arrays.sort(strArr);
        StringBuffer sbf = new StringBuffer();
        for (String s : strArr) {
               sbf.append(s);
        }
        String sha1 = SecurityKitUtil.sha1(sbf.toString());

        if(signature.equals(sha1)){

            return echostr;
        }
        return null;
    }
    @PostMapping("/message")
    @ResponseBody
    public Object message(HttpServletRequest request) throws IOException {
//        ServletInputStream inputStream = request.getInputStream();
//        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//        String temp=null;
//        while ((temp=bufferedReader.readLine())!=null){
//            System.out.println(temp);
//        }
        String msg = autoSendMsg(request);
        return msg;
    }

    private String autoSendMsg(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        Map<String, String> revMsg = getMessage(inputStream);
        String msgType = revMsg.get("msgType");
        String toUser = revMsg.get("toUserName");
        String fromUser = revMsg.get("fromUserName");
        String eve = revMsg.get("event");
        String eveKey = revMsg.get("eventKey");

        if (MsgType.MSG_TYPE_TEXT.equals(msgType)) {
            //回复文本消息
            String content = revMsg.get("content");
            content = (content != null && content.trim().length() > 0) ? content : "换一个关键字!";
            String msg = this.sendTextMsg(fromUser, toUser, content);
            return msg;
        } else if (MsgType.MSG_TYPE_IMAGE.equals(msgType)) {
            //图片消息
            String mediaId = "hCo0JfK-UWuOPdSfZZLwqSE7XmELiR_ewpG_bevndFjKHmSAl755kpH9lPhg-oWe";
            String msg = this.sendImageMsg(fromUser, toUser, mediaId);
            return msg;
        } else if(MsgType.MSG_TYPE_EVENT.equals(msgType)){
            String msg = this.caiquan(toUser,fromUser,eve,eveKey);
            return msg;
        } else {
            //正在开发 消息
            String msg = this.sendTextMsg(fromUser, toUser, "正在开发中...,暂支持：文本和图片");
            return msg;
        }

    }

    private Map<String,String> getMessage(InputStream inputStream){
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            Element root = document.getRootElement();
            String toUserName = root.elementText("ToUserName");
            String fromUserName = root.elementText("FromUserName");
            String msgType = root.elementText("MsgType");
            String event = root.elementText("Event");
            String eventKey = root.elementText("EventKey");
            Map<String,String> map=new HashMap<>();
            map.put("toUserName",toUserName);
            map.put("fromUserName",fromUserName);
            map.put("msgType",msgType);
            if ("text".equals(msgType)) {
                String content = root.elementText("Content");
                map.put("content", content);
            }
            if(event!=null){
                map.put("event",event);
            }
            if(eventKey!=null){
                map.put("eventKey",eventKey);
            }
            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
    private String sendTextMsg(String toUser, String fromUser, String content) {


        TextMsg textMsg = new TextMsg();
        textMsg.setToUserName(toUser);
        textMsg.setFromUserName(fromUser);
        textMsg.setMsgType(MsgType.MSG_TYPE_TEXT);
        textMsg.setCreateTime(new Date().getTime());

        //人工智能
        content = content.replace("吗", "");
        content = content.replace("么", "");
//        content = content.replace("我", "我也");
        content = content.replace("?", "!");
        content = content.replace("？", "!");

        textMsg.setContent(content);

        //对象转为xml文件
        XStream xStream = new XStream();
        xStream.alias("xml", TextMsg.class);
        String s = xStream.toXML(textMsg);

        System.out.println("回复文本消息:" + s);
        return s;
    }


    /**
     * 回复图片消息
     *
     * @param toUser
     * @param fromUser
     * @param mediaId
     * @return
     */
    private String sendImageMsg(String toUser, String fromUser, String mediaId) {

        ImageMsg imageMsg= new ImageMsg();

        imageMsg.setToUserName(toUser);
        imageMsg.setFromUserName(fromUser);
        imageMsg.setMsgType(MsgType.MSG_TYPE_IMAGE);
        imageMsg.setCreateTime(new Date().getTime());

        ImageInfo imageInfo = new ImageInfo();
        imageInfo.setMediaId(mediaId);
        imageMsg.setImage(imageInfo);

        XStream xStream = new XStream();
        xStream.alias("xml", ImageMsg.class);
        xStream.alias("Image", ImageInfo.class);

        String xml = xStream.toXML(imageMsg);
        System.out.println("回复图片消息:" + xml);
        return xml;
    }



    private  String caiquan(String toUser,String fromUser,String event,String eventKey){
//        CaiQuan caiQuan = new CaiQuan();
//        caiQuan.setToUserName(toUser);
//        caiQuan.setFromUserName(fromUser);
//        caiQuan.setCreateTime(new Date().getTime());
//        caiQuan.setMsgType(MsgType.MSG_TYPE_EVENT);
//        caiQuan.setEventKey(event);
//        caiQuan.setEvent(eventKey);
        String [] cq={cqType.GAME_01_SHITOU,cqType.GAME_01_JIANDAN,cqType.GAME_01_BU};
        Random random = new Random();
        int num = random.nextInt(3);
        String msg="";
        if(eventKey.equals(cq[num])){
            msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：看来是有bear来啊！";

        }else{
            if(eventKey.equals(cqType.GAME_01_SHITOU)&&cq[num].equals(cqType.GAME_01_JIANDAN)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：年轻人不讲武德，来骗！来偷袭，我一个程序！";

            }else if(eventKey.equals(cqType.GAME_01_SHITOU)&&cq[num].equals(cqType.GAME_01_BU)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：我全部防出去了啊！";

            }else if(eventKey.equals(cqType.GAME_01_JIANDAN)&&cq[num].equals(cqType.GAME_01_SHITOU)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：我全部防出去了啊！";

            }
            else if(eventKey.equals(cqType.GAME_01_JIANDAN)&&cq[num].equals(cqType.GAME_01_BU)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：年轻人不讲武德，来骗！来偷袭，我一个程序！";

            }
            else if(eventKey.equals(cqType.GAME_01_BU)&&cq[num].equals(cqType.GAME_01_SHITOU)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：年轻人不讲武德，来骗！来偷袭，我一个程序！";

            }
            else if(eventKey.equals(cqType.GAME_01_BU)&&cq[num].equals(cqType.GAME_01_JIANDAN)){
                msg="你出的是:"+eventKey+"\n系统出的是:"+cq[num]+"\n本局结果：我全部防出去了啊！";

            }
        }

        return this.sendTextMsg(fromUser, toUser, msg);

    }

    public static void main(String[] args) {
        String [] cq={cqType.GAME_01_SHITOU,cqType.GAME_01_JIANDAN,cqType.GAME_01_BU};
        System.out.println(cq[0]);
    }
}
